package com.xmqian.app.common.utils.apiadapter;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.view.DisplayCutout;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowManager;


import com.coszero.utilslibrary.utils.LogX;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * @author Administrator
 * @date 2019/4/24
 * @desc 9.0屏幕缺口适配方案
 */
public class DisplayCutoutUtils {
    WeakReference weakReference;
    Activity myContext;
    /**
     * 允许延伸到刘海区域
     * 屏幕短边有cutout，会延伸过去；若cutout在长边，一定不会延伸过去。
     * 在长边有cutout的情况，会排出在外
     */
    public static final int SHORT_EDGES = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
    /**
     * 不允许使用刘海区域
     */
    public static final int NEVER = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;

    public DisplayCutoutUtils(Context context) {
        weakReference = new WeakReference(context);
        myContext = (Activity) weakReference.get();
    }

    public static DisplayCutoutUtils newInstance(Context context) {
        DisplayCutoutUtils cutoutUtils = new DisplayCutoutUtils(context);
        return cutoutUtils;
    }

    @TargetApi(28)
    public void init() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            View decorView = myContext.getWindow().getDecorView();
            WindowInsets rootWindowInsets = decorView.getRootWindowInsets();
            if (rootWindowInsets != null) {
                DisplayCutout cutout = rootWindowInsets.getDisplayCutout();
                List<Rect> boundingRects = cutout.getBoundingRects();
                if (boundingRects != null && boundingRects.size() > 0) {
                    String msg;
                    for (Rect rect : boundingRects) {
                        msg = "left-" + rect.left;
                        LogX.d("####屏幕信息：", msg);
                    }
                }
            }
        }
    }

    /**
     * 设置缺口屏的显示模式,最好在onCreate中使用
     * -默认不可使用刘海区域，非全面平可以使用：MODE_DEFAULT=0
     * -允许延伸到刘海区域SHORT_EDGES=1
     * -不允许使用刘海区域NEVER=2
     */
    @TargetApi(28)
    public void setDisplayCutouMode(int showMode) {
        if (Build.VERSION.SDK_INT >= 28) {
            WindowManager.LayoutParams lp = myContext.getWindow().getAttributes();
            if (showMode != 0) {
                lp.layoutInDisplayCutoutMode = showMode;
            } else {
                lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            }
            myContext.getWindow().setAttributes(lp);
            myContext.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
    }
}
